package handlers

import (
	"car-order-mgmt/cache"
	"car-order-mgmt/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func CarAdd(c *gin.Context) {
	CarCode := c.PostForm("CarCode")
	CarName := c.PostForm("CarName")
	CarNum := c.PostForm("CarNum")
	car := models.Car{
		CarCode: CarCode,
		CarName: CarName,
		CarNum:  CarNum,
	}
	models.DB.Create(&car)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	OrderNO := c.PostForm("OrderNO")
	FormAddress := c.PostForm("FormAddress")
	ToAddress := c.PostForm("ToAddress")
	Cid, _ := strconv.Atoi(c.PostForm("Cid"))
	order := models.Order{
		OrderNO:     OrderNO,
		FormAddress: FormAddress,
		ToAddress:   ToAddress,
		Cid:         Cid,
	}
	models.DB.Create(&order)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderList(c *gin.Context) {
	var orderlist []models.OrderList
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	off := (page - 1) * size
	redis_key := "orderList_" + strconv.Itoa(page)
	data, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if data == "" {
		models.DB.Table("orders").
			Joins("LEFT JOIN cars ON orders.cid = cars.id").
			Select(
				"cars.car_code AS CarCode",
				"cars.car_name AS CarName",
				"cars.car_num AS CarNum",
				"orders.order_no AS OrderNO",
				"orders.form_address AS FormAddress",
				"orders.to_address AS ToAddress",
			).Offset(off).Limit(size).Debug().Find(&orderlist)
		jsonData, _ := json.Marshal(orderlist)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(data), &orderlist)
	}
	var count int64
	models.DB.Model(&models.Order{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  orderlist,
		"count": count,
	})
	return
}

/*
SELECT

	cars.car_code,
	cars.car_name,
	cars.car_num,
	orders.order_no,
	orders.form_address,
	orders.to_address

FROM

	orders
	JOIN cars ON orders.cid = cars.id
*/
func OrderDetail(c *gin.Context) {
	var order models.Order
	id := c.Query("id")
	redis_key := "order_detail_" + id
	data, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if data == "" {
		models.DB.First(&order, id)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(data), &order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": order,
	})
	return
}
